package com.aptemo.webetek.server;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aptemo.webetek.client.enums.EnumPickStatus;
import com.aptemo.webetek.client.enums.EnumBetType;
import com.aptemo.webetek.server.data.PMF;
import com.aptemo.webetek.server.data.Pick;
import com.aptemo.webetek.server.data.Stake;
import com.aptemo.webetek.shared.StatisticsBean;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

public class UserStatisticsWorker
		extends HttpServlet
{

	/**
	 * 
	 */
	private static final long		serialVersionUID	= -1562392302403920611L;

	private final MemcacheService	memcache			= MemcacheServiceFactory.getMemcacheService();
	private static final Logger		log					= Logger.getLogger(UserStatisticsWorker.class.getName());

	private static final String		STATS_PREFIX		= "STATISTICS/";

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		String userId = req.getParameter("key");
		Key userKey = KeyFactory.stringToKey(userId);

		StatisticsBean stats = new StatisticsBean();

		int cntWon = 0;
		int cntPlaced = 0;
		int cntActiveBets = 0;
		int cntAllBets = 0;
		int cntAllStakes = 0;
		double sumEarnings = 0;
		double sumInvested = 0;

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
			// WebetekUser user = pm.getObjectById(WebetekUser.class, userKey);

			// Query qstakes = pm.newQuery("select from " +
			// Stake.class.getName() + " where player == :p1 && status != :p2");
			// List<Stake> stakes = (List<Stake>) qstakes.execute(user,
			// EnumStakeStatus.OPENED);
			// List<Stake> stakes = user.getStakes();
			Query query = pm.newQuery(Stake.class);
			query.setFilter("parentKey == :p1");
			List<Stake> stakes = (List<Stake>) query.execute(userKey);

			for (Stake stake : stakes)
			{
				List<Key> pickkeys = stake.getPickKeys();
				cntPlaced += pickkeys.size();

				// TODO try keys_only query
				Query qcountpicks = pm.newQuery("select COUNT(id) from " + Pick.class.getName() + " where :p1.contains(id) && status == :p2");
				int won = (Integer) qcountpicks.execute(pickkeys, EnumPickStatus.WON);
				cntWon += won;

				sumEarnings += stake.getEarnings();
				if (stake.getBetType() == EnumBetType.SINGLE)
				{
					sumInvested += stake.getAmount() * pickkeys.size();
					cntAllBets += pickkeys.size();
				}
				else
				{
					cntAllBets++;
				}
				cntAllStakes++;
			}

			stats.setNoOfUsers(1);
			stats.setNoOfBetsPlaced(cntPlaced);
			stats.setNoOfBetsWon(cntWon);
			stats.setNoOfActiveBets(cntActiveBets);
			stats.setEarnings(sumEarnings);
			stats.setAmountInvested(sumInvested);
			stats.setNoOfAllBets(cntAllBets);

			log.info("Writing to memcache. UserId=" + userId + " - won=" + stats.getNoOfBetsWon());

			// cache...
			memcache.put(STATS_PREFIX + userId, stats);
		}
		finally
		{
			pm.close();
		}

	}
}
